import { createSlice,createAsyncThunk } from "@reduxjs/toolkit";
import * as API from "../API/http"
let initialState={
    shoplist:[]
}
const todosSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {
   getshop(state,action){
    state.shoplist=action.payload
   },
   getadd(state,action){
    state.shoplist.push(action.payload)
   },
   getsdit(state,action){
   let i= state.shoplist.findIndex(item=>{
      return item.id==action.payload.id
    })
    state.shoplist[i]=action.payload
   },
   getdel(state,action){
  state.shoplist=  state.shoplist.filter(item=>{
      return item.id!=action.payload
    })
   }
  },
});

export const { getshop,getadd,getsdit,getdel } = todosSlice.actions;
export default todosSlice.reducer;
export let async_shop=createAsyncThunk('async_shop',async(_,store)=>{
let res=await API.httpshop()
store.dispatch(getshop(res))
})
export let async_add=createAsyncThunk('async_add',async(obj,store)=>{
 let res=await API.httpadd(obj)
store.dispatch(getadd(res))
})
export let async_edit=createAsyncThunk('async_edit',async(obj,store)=>{
let res=await  API.httpedit(obj)
store.dispatch(getsdit(res))
})
export let async_del=createAsyncThunk('async_del',async(id,store)=>{
 await API.httpdel(id)
  store.dispatch(getdel(id))
})